package com.jay.scan

import android.Manifest
import android.app.AlertDialog
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.util.Size
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.common.util.concurrent.ListenableFuture
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class ScanActivity : AppCompatActivity() {

    companion object {
        val TAG = "scan"
        val REQUEST_CODE = 200
    }

    private var executorService: ExecutorService = Executors.newSingleThreadExecutor()
    private lateinit var previewView: PreviewView
    private lateinit var cameraProvider: ProcessCameraProvider

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan)

        previewView = findViewById(R.id.previewView)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                openCamera()
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.CAMERA),
                    REQUEST_CODE
                )
            }
        } else {
            openCamera()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera()
            } else {
                Log.e(TAG, "permission is denied")
                showOpenCameraDialog()
            }
        }
    }

    private fun showOpenCameraDialog() {
        AlertDialog.Builder(this)
            .setTitle("权限提示")
            .setMessage("扫码需要开启摄像头权限,请开启相应权限")
            .setPositiveButton("确认") { dialog, _ ->
                dialog.dismiss()
                var showTips = ActivityCompat.shouldShowRequestPermissionRationale(
                    this,
                    Manifest.permission.CAMERA
                )
                Log.e(TAG, "should show permission tips $showTips")

                if (!showTips) {
                    IntentUtils.startPermission(this, this.packageName)
                }
            }
            .create()
            .show()
    }

    private fun openCamera() {
        var listenableFuture: ListenableFuture<ProcessCameraProvider> =
            ProcessCameraProvider.getInstance(this)
        listenableFuture.addListener(
            {
                cameraProvider = listenableFuture.get()
                bindCamera()
            },
            ContextCompat.getMainExecutor(this)
        )
    }

    private fun bindCamera() {
        cameraProvider.unbindAll()

        var rotation = previewView.display.rotation
        val preview = Preview.Builder()
            .setTargetRotation(rotation)
            .build()

        val cameraSelector = CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build()

        val imageAnalysis = ImageAnalysis.Builder()
            .setTargetResolution(Size(1920, 1080))
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .setTargetRotation(rotation)
            .build()

        imageAnalysis.setAnalyzer(executorService, ScanImageAnalysis())

        cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis)
        preview.setSurfaceProvider(previewView.surfaceProvider)
    }

    class ScanImageAnalysis : ImageAnalysis.Analyzer {
        override fun analyze(image: ImageProxy) {
            Log.d(TAG, "on new image")
            val bitmap = ImageUtils.transImageProxyToBitmap(image)
            image.close()
        }
    }
}